import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store"; // 这是 Vuex store
import { createPinia, PiniaVuePlugin } from "pinia"; // 引入 Pinia
import gsap from "gsap";
import "animate.css";
import "@/styles/im.scss"; // 导入 IM 样式
import VueLazyload from "vue-lazyload";
import VueMeta from "vue-meta";

// 新增IM相关导入
import request from "@/utils/request";
import eventBus from "@/utils/im/eventBus";
import * as socketApi from "@/utils/im/wssocket";
import * as messageType from "@/utils/im/messageType";
import emotion from "@/utils/im/emotion";
import url from "@/utils/im/url";
import element from "@/utils/im/element";
import * as enums from "@/utils/im/enums";
import * as date from "@/utils/im/date";
import "@/directives/dialogDrag";
import useChatStore from "@/store/pinia/chatStore";
import useFriendStore from "@/store/pinia/friendStore";
import useGroupStore from "@/store/pinia/groupStore";
import useUserStore from "@/store/pinia/userStore";
import useConfigStore from "@/store/pinia/configStore";

// 添加Vue Clipboard2
import VueClipboard from "vue-clipboard2";
Vue.use(VueClipboard);

import ScrollTrigger from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);

// 配置 vue-lazyload
Vue.use(VueLazyload, {
  preLoad: 1.3,
  error:
    "https://kingcola-blog.oss-cn-hangzhou.aliyuncs.com/img-error.jpg",
  loading:
    "https://kingcola-blog.oss-cn-hangzhou.aliyuncs.com/lazy.gif",
  attempt: 1,
  observer: true,
  observerOptions: {
    rootMargin: "0px",
    threshold: 0.1,
  },
});

import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
Vue.use(ElementUI);

// 新增IM相关全局挂载
Vue.prototype.$wsApi = socketApi;
Vue.prototype.$msgType = messageType;
Vue.prototype.$date = date;
Vue.prototype.$http = request;
Vue.prototype.$emo = emotion;
Vue.prototype.$url = url;
Vue.prototype.$elm = element;
Vue.prototype.$enums = enums;
Vue.prototype.$eventBus = eventBus;

//表情组件
import EmojiPicker from "@/components/common/EmojiPicker.vue";
Vue.component("mj-emoji", EmojiPicker);

//颜色选择器组件
import ColorPicker from "@/components/common/ColorPicker.vue";
Vue.component("mj-color-picker", ColorPicker);

import ClickOutside from "@/directives/clickOutside";
Vue.directive("click-outside", ClickOutside);

//加载组件
import loading from "./directives/loading";
Vue.directive("loading", loading);

//高亮
import "highlight.js/styles/atom-one-dark.css";
// 引入自定义代码高亮工具
import highlightUtil, {
  renderContent,
  applyHighlighting,
} from "@/utils/highlight";
import "@/utils/highlight.css";

import { animateOnScroll } from "./directives/animate";
Vue.directive("animate-on-scroll", animateOnScroll);

//图片预览组件
import ImagePreview from "@/components/common/ImagePreview.vue";
Vue.component("mj-image-preview", ImagePreview);

//链接跳转提示框组件
import LinkJumpPrompt from "@/components/common/LinkJumpPrompt.vue";
Vue.component("mj-link-jump-prompt", LinkJumpPrompt);

//链接跳转指令
import LinkJump, {
  linkJump,
  autoLinkJump,
  processPageLinks,
} from "./directives/linkJump";
Vue.use(LinkJump);
Vue.directive("link-jump", linkJump);
Vue.directive("auto-link-jump", autoLinkJump);

// 在页面加载完成后处理所有外部链接
window.addEventListener("DOMContentLoaded", () => {
  // 延迟一点执行，确保所有内容都已渲染
  setTimeout(() => {
    if (typeof processPageLinks === "function") {
      try {
        processPageLinks({
          selector: "a", // 处理所有链接
          exclude: [
            ".no-jump",
            ".nav-link",
            ".social-btn", // 排除社交按钮
            ".author-card a", // 排除作者卡片中的链接
            '[href^="javascript:"]', // 排除javascript:开头的链接
            ".el-dropdown-menu a", // 排除下拉菜单中的链接
          ],
        });
        console.log("全局链接跳转处理已初始化");
      } catch (error) {
        console.error("Error initializing global link handling:", error);
      }
    } else {
      console.warn(
        "processPageLinks function not available for DOMContentLoaded"
      );
    }
  }, 500);
});

// 为了支持 HMR
if (import.meta.hot) {
  import.meta.hot.accept();
}

import mavonEditor from "mavon-editor";
import "mavon-editor/dist/css/index.css";
Vue.use(mavonEditor);

// 全局挂载代码高亮工具
Vue.prototype.$highlight = {
  render: renderContent,
  apply: applyHighlighting,
  utils: highlightUtil,
};

// 导入全局Loading组件
import LoadingComponent from "@/components/common/Loading.vue";

// 注册全局Loading组件方法
const Loading = {
  install(Vue) {
    try {
      // 创建一个全局可访问的加载组件实例
      const LoadingConstructor = Vue.extend(LoadingComponent);
      const loadingInstance = new LoadingConstructor({
        propsData: {
          autoDetectReady: true, // 启用自动检测功能
        },
      });

      // 挂载到文档之外
      loadingInstance.$mount();
      document.body.appendChild(loadingInstance.$el);

      // 添加全局方法
      Vue.prototype.$showLoading = (target) => {
        console.log("全局方法 $showLoading 被调用, 目标:", target);
        if (store && store.dispatch) {
          if (target) {
            // 设置加载目标类型
            store.dispatch("showLoading", target);
          } else {
            store.dispatch("showLoading");
          }
        } else {
          console.warn("Store not available when calling $showLoading");
          // 直接调用加载组件实例方法作为后备
          loadingInstance.showLoading && loadingInstance.showLoading();
        }
      };

      Vue.prototype.$hideLoading = () => {
        console.log("全局方法 $hideLoading 被调用");
        if (store && store.dispatch) {
          store.dispatch("contentReady");
        } else {
          console.warn("Store not available when calling $hideLoading");
          // 直接调用加载组件实例方法作为后备
          loadingInstance.hideLoading && loadingInstance.hideLoading();
        }
      };

      // 提供通知内容已准备好的方法
      Vue.prototype.$contentReady = function () {
        console.log("全局方法 $contentReady 被调用");

        // 防止递归调用和重复通知
        if (window._isNotifyingContentReady) {
          console.warn(
            "Already notifying content ready, skipping $contentReady call"
          );
          return;
        }

        window._isNotifyingContentReady = true;

        try {
          if (loadingInstance && loadingInstance.notifyContentReady) {
            loadingInstance.notifyContentReady();
          } else if (store && store.dispatch) {
            store.dispatch("contentReady");
          }
        } catch (error) {
          console.error("Error in $contentReady:", error);
        } finally {
          // 确保标志被重置
          setTimeout(() => {
            window._isNotifyingContentReady = false;
          }, 100);
        }
      };

      // 为 Vue 原型添加处理加载状态的方法
      Vue.prototype.$processPageLinks = function (options) {
        if (typeof processPageLinks === "function") {
          try {
            processPageLinks(options);

            // 防止递归调用和重复通知
            if (window._isNotifyingContentReady) {
              console.log("已经在通知内容准备好，跳过处理页面链接后的通知");
              return;
            }

            // 处理完页面链接后，通知内容已准备好
            setTimeout(() => {
              console.log("处理页面链接完成，通知内容准备好");
              if (
                !window._isNotifyingContentReady &&
                loadingInstance &&
                loadingInstance.notifyContentReady
              ) {
                this.$contentReady();
              }
            }, 100);
          } catch (error) {
            console.error("Error processing page links:", error);
          }
        } else {
          console.warn("processPageLinks function not available");
        }
      };

      // 添加全局混入，在组件挂载完成后自动检测内容准备状态
      Vue.mixin({
        mounted() {
          // 仅在路由组件中执行
          if (
            this.$route &&
            this.$parent &&
            this.$parent.$el &&
            this.$parent.$el.tagName
          ) {
            // 页面组件可能需要更长的时间来渲染和加载数据
            setTimeout(() => {
              if (store && store.state && store.state.isLoading) {
                console.log(
                  "组件挂载完成，可能需要通知内容准备好:",
                  this.$options.name
                );
                if (loadingInstance && loadingInstance.checkContentReady) {
                  loadingInstance.checkContentReady();
                }
              }
            }, 500);
          }
        },
      });
    } catch (error) {
      console.error("Error installing Loading plugin:", error);
    }
  },
};

// 使用Loading插件
Vue.use(Loading);

Vue.use(VueMeta);

Vue.config.productionTip = false;

import "virtual:svg-icons-register";

// 注册全局组件
import SvgIcon from "@/components/SvgIcon/index.vue";
Vue.component("svg-icon", SvgIcon);

// 在生产环境中禁用F12和右键菜单
// if (process.env.NODE_ENV === "production") {
//   // 禁用开发者工具的快捷键
//   window.addEventListener("keydown", function (e) {
//     if (
//       e.key === "F12" || // F12
//       (e.ctrlKey && e.shiftKey && e.key === "I") || // Ctrl+Shift+I
//       (e.ctrlKey && e.shiftKey && e.key === "J") || // Ctrl+Shift+J
//       (e.ctrlKey && e.key === "U") // Ctrl+U (查看源代码)
//     ) {
//       e.preventDefault();
//     }
//   });

//   // 禁用右键上下文菜单
//   window.addEventListener("contextmenu", function (e) {
//     e.preventDefault();
//   });
// }

// 注册 Pinia 插件
Vue.use(PiniaVuePlugin);
// 创建 Pinia 实例
const pinia = createPinia();

// 创建Vue实例
const app = new Vue({
  router,
  store, // Vuex store
  pinia, // Pinia store
  metaInfo: {
    title: "🎯 KingCola-ICG Blog",
    titleTemplate: "%s - 始于代码，不止于代码",
    htmlAttrs: {
      lang: "zh-CN",
      amp: true,
    },
    meta: [
      { charset: "utf-8" },
      {
        name: "description",
        content:
          "KingCola-ICG Blog是一个专注于技术分享的博客，内容涵盖前端、后端、运维、云原生等领域。",
      },
      {
        name: "keywords",
        content:
          "KingCola-ICG,博客,技术博客,前端,后端,Vue,React,Node.js,云原生",
      },
    ],
  },
  render: (h) => h(App),
}).$mount("#app");

// Pinia stores全局挂载 - 通过mixin提供computed属性访问
Vue.mixin({
  computed: {
    chatStore() {
      return useChatStore();
    },
    friendStore() {
      return useFriendStore();
    },
    groupStore() {
      return useGroupStore();
    },
    userStore() {
      return useUserStore();
    },
    configStore() {
      return useConfigStore();
    },
  },
});

// 路由变化后重新处理页面链接
router.afterEach(() => {
  // 等待DOM更新后处理
  setTimeout(() => {
    if (
      Vue.prototype.$processPageLinks &&
      typeof Vue.prototype.$processPageLinks === "function"
    ) {
      try {
        Vue.prototype.$processPageLinks({
          selector: "a",
          exclude: [
            ".no-jump",
            ".nav-link",
            ".social-btn", // 排除社交按钮
            ".author-card a", // 排除作者卡片中的链接
            '[href^="javascript:"]', // 排除javascript:开头的链接
            ".el-dropdown-menu a", // 排除下拉菜单中的链接
          ],
        });
      } catch (error) {
        console.error("Error processing page links after route change:", error);
      }
    }
  }, 500);
});
